<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120"
    >
      <el-form-item label="产品名称" prop="coalName">
        <el-input v-model="formData.coalName" :maxlength="20" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" :maxlength="100" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as production from '@/api/production'
const emit = defineEmits(['success'])
const formRef = ref()
const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData: Record<string, any> = ref({
  id: undefined,
  coalName: undefined,
  remark: undefined
})

const formRules = reactive({
  coalName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }]
})

const open = async (id?: number) => {
  resetFn()
  dialogVisible.value = true
  formData.value.id = id
  if (id) {
    dialogTitle.value = '编辑'
    getCoalManageById(id)
  } else {
    dialogTitle.value = '新增'
  }
}

const getCoalManageById = async (id) => {
  const res = await production.getCoalManageById({ id })
  formData.value.coalName = res?.coalName
  formData.value.remark = res?.remark
}

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    formLoading.value = true
    if (formData.value.id) {
      await production.coalManageUpdate(formData.value)
    } else {
      await production.coalManageCreate(formData.value)
    }
    message.success(t('common.operateSuccess'))
    dialogVisible.value = false
    resetFn()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetFn = () => {
  formData.value = {
    id: undefined,
    invalidReason: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
